package cn.jsu.oj.dispatchServer.satellite.mode.subscribe;

import cn.jsu.oj.dispatchServer.satellite.pojo.net.RequestNet;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 中情局面壁者
 *
 * @author shan
 * @date 2022/06/29
 */
@Component
public abstract class AbsCiaObservable implements Observable {

    /**
     * 观察者map
     */
    private final Map<String, Observer> observerMap;
    
    private final Map<String, Byte> observerStatusMap;

    /**
     * 中情局面壁者初始化
     */
    public AbsCiaObservable() {
        this.observerMap = new ConcurrentHashMap<>();
        this.observerStatusMap = new ConcurrentHashMap<>();
    }
    
    public Map<String, Byte> getObserverStatusMap() {
        return this.observerStatusMap;
    }

    /**
     * 注册客户端观察者
     *
     * @param observer 观察者
     * @param identity 身份
     */
    @Override
    public void registerObserver(Observer observer, String identity) {
        this.observerMap.put(identity, observer);
        if (!this.observerStatusMap.containsKey(identity)) {
            this.observerStatusMap.put(identity, (byte) 1);
        }
        this.observerStatusMap.replace(identity, (byte) 1);
    }

    /**
     * 移除客户端观察者
     *
     * @param identity 身份
     */
    @Override
    public void removeObserver(String identity) {
        observerMap.remove(identity);
    }

    /**
     * 通知客户端观察者
     *
     * @param requestNet 指令net包
     */
    @Override
    public void notifyObserver(Object requestNet) {
        this.observerMap.forEach((key, value) -> value.update(requestNet));
        this.observerStatusMap.replace(((RequestNet) requestNet).getIdentity(), (byte) 0);
    }
}
